/* eslint-disable */
/**
 * 富文本编辑器
 */
import React, {Component} from 'react';
import {connect} from 'dva';
import {EditorState, convertToRaw, convertFromRaw, ContentState} from 'draft-js';
import {Editor} from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import '../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styles from './RichText.less';
import commonService from '../../services/commonService';

class RichText extends Component {
  // state = {
  //   editorState: EditorState.createEmpty(),
  // }
  constructor(props) {
    super(props);
    const html = props.value;
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.state = {
        editorState,
      };
    }
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });
    let text = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    this.props.onChange(text)
  };

  componentDidMount() {

  };

  uploadImageCallBack = (file) => {
    return new Promise(
      (resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/ehscare/fileUpload/save');
        xhr.setRequestHeader('Authorization', 'Client-ID XXXXX');
        const data = new FormData();
        data.append('file', file);
        xhr.send(data);
        xhr.addEventListener('load', () => {
          const response = JSON.parse(xhr.responseText);
          const url = `http://192.168.1.115:9004/fss/download?fileId=${response.ret.relativeFolder}`;
          const myResponse = {
            "data": {
              "link": url
            }
          };
          resolve(myResponse);
        });
        xhr.addEventListener('error', () => {
          const error = JSON.parse(xhr.responseText);
          reject(error);
        });
      }
    );
  };

  render() {
    let t = this;
    const {editorState} = this.state;
    return (
      <div>
        <Editor
          editorState={editorState}
          editorClassName={styles['border-editor']}
          localization={{
            locale: 'zh',
          }}
          onEditorStateChange={t.onEditorStateChange}
          toolbar={{
            inline: {inDropdown: true},
            list: {inDropdown: true},
            textAlign: {inDropdown: true},
            link: {inDropdown: true},
            history: {inDropdown: true},
            image: {
              uploadCallback: t.uploadImageCallBack,
              alt: {present: true, mandatory: false},
              previewImage: true,
            },
          }}
        />
      </div>
    )
  }
}
function mapStateToProps(state) {
  return {};
}
export default connect(mapStateToProps)(RichText);
